import Vanilla.UI

// BALL
class Ball (Gadget):
	override MinSize as Size:
		get:
			return Size(30,30)
	
	override def Draw (b as Brush):
		b.Draw(Rect(Size))
		b.Colour = Colour.Red.Alpha(0.5)
		b.Fill()

	def constructor (p as Box):
		super(p)

// PADDLE
class Paddle (Gadget):
	def constructor (p as Box):
		super(p)

// PING BOX
class PingBox (Box):
	Paddle as Paddle
	
	Ball as Ball
	
	enum Dir:
		NW
		NE
		SE
		SW
	Direction as Dir = Dir.NW
	
	public Timer as UITimer
	
	Lives as int
	
	def constructor (p as Box):
		super(p)
		
		Paddle = Paddle(self)
		
		Ball = Ball(self)
		
		Setup()
	
	def Setup():
		Lives = 5
		
		Paddle.Rect = Rect(0,0,10,90)
		Ball.Rect = Rect(Size.Width/2 - 15, Size.Height/2 - 15, Size.Width/2 + 15, Size.Height/2 + 15)
		
		Timer = UITimer(50, Cycle)
	
	override def ContainsMouseAt (x as double, y as double):
		return Size.Contains(x,y)
	
	def Cycle ():
		// Move the ball
		if Direction == Dir.NW:
			Ball.Position = Position(Ball.Position.X-15,Ball.Position.Y-15)
		elif Direction == Dir.SW:
			Ball.Position = Position(Ball.Position.X-15,Ball.Position.Y+15)
		elif Direction == Dir.NE:
			Ball.Position = Position(Ball.Position.X+15,Ball.Position.Y-15)
		elif Direction == Dir.SE:
			Ball.Position = Position(Ball.Position.X+15,Ball.Position.Y+15)
		
		// Check for a hit
		if Paddle.Rect.Overlaps(Ball.Rect):
			if Direction == Dir.NW:
				Direction = Dir.NE
			elif Direction == Dir.SW:
				Direction = Dir.SE
		
		// Check for rebound/score
		if Ball.Rect.X < 0:
			if Parent isa Window:
				(Parent as Window).Title = "Ping - ${Lives} left!"
			Lives--
			if Lives == 0:
				if Parent isa Window:
					(Parent as Window).Title = "Ping"
				Timer.Stop()
				AlertWindow("You lost!", {Setup()})	
					
			Ball.Rect = Rect(Size.Width/2 - 15, Size.Height/2 - 15, Size.Width/2 + 15, Size.Height/2 + 15)
			Direction = Dir.NW
		elif Ball.Rect.Y < 0:
			if Direction == Dir.NW:
				Direction = Dir.SW
			elif Direction == Dir.NE:
				Direction = Dir.SE
		elif Ball.Rect.Y2 > Size.Height:
			if Direction == Dir.SW:
				Direction = Dir.NW
			elif Direction == Dir.SE:
				Direction = Dir.NE
		elif Ball.Rect.X2 > Size.Width:
			if Direction == Dir.NE:
				Direction = Dir.NW
			elif Direction == Dir.SE:
				Direction = Dir.SW
	
	override def MouseMotion (x as double, y as double):
		Paddle.Position = Position(0, y-Paddle.Size.Height/2)

// PING WINDOW
class PingWindow (MainWindow):
	Ping as PingBox

	def constructor ():
		super("Ping")
		Size = Size(400,300)
		Ping = PingBox(self)
	
	override def Close ():
		Ping.Timer.Stop()
		super()
		
